package com.zlzlib.log.config;


import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.zlzlib.common.util.IpUtil;
import com.zlzlib.common.util.SpringContextUtil;
import com.zlzlib.log.bean.enums.LogType;
import com.zlzlib.log.bean.po.LogPo;
import com.zlzlib.log.service.LogSaveService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 自定义的log存储
 *
 * @DateTime: 2024/7/15 11:05
 * @Author zlz
 * @Version 1.0
 */
public class MgLogAppender extends AppenderBase<ILoggingEvent> {

    @Override
    protected void append(ILoggingEvent eventObject) {
        LogSaveService logSaveService = SpringContextUtil.getBean(LogSaveService.class);
        LogPo po = new LogPo();
        po.setThread(eventObject.getThreadName());
        po.setLogType(LogType.print.getValue());
        po.setResult(eventObject.getMessage());
        po.setCreateTime(new Date(eventObject.getTimeStamp()));
        if (eventObject.getCallerData().length > 0) {
            StackTraceElement element = eventObject.getCallerData()[0];
            po.setMethod(element.getMethodName());
            po.setClassName(element.getClassName());
        }
        if (RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes()).getRequest();
            po.setIp(IpUtil.getIpAddress(request));
        }
        logSaveService.saveLog(po);
    }
}
